
package action;

import beans.UserBean;
import db.Forum;
import db.Message;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;

/**
 * Delete message from forum.
 * @author Tomas CASTA
 */
@UrlBinding("/messageDelete.action")
public class DeleteMessageActionBean implements ActionBean {

    /** action context */
    private ActionBeanContext context;
    /** forum */
    private Forum forum;

    public ActionBeanContext getContext() {
        return context;
    }

    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    /**
     * Delete message from forum.
     * @return Resolution
     */
    public Resolution delete() {

        /* User is logged */
        if (null != context.getRequest().getSession().getAttribute("user")) {

            /* Get user info from session */
            UserBean user = (UserBean) context.getRequest().getSession().getAttribute("user");

            /* User is admin */
            if (user.getAdmin() == 1) {
                forum = new Forum();
                forum.setDb(this.context.getServletContext());

                /* Parse id from URI */
                try {
                    /* Message id to delete */
                    int idDel = Integer.valueOf(context.getRequest().getParameter("idDelete"));

                    /* Forum id to show */
                    int idShow = Integer.valueOf(context.getRequest().getParameter("idShow"));
                    Message message = new Message();
                    message.setDb(this.context.getServletContext());

                    /* Delete message */
                    int result = message.deleteMessage(idDel);

                    /* Last message in forum, forum was deleted */
                    if (result == 2){
                        return new ForwardResolution("/index.action");
                    }


                    /* Show forum without deleted message */
                    forum.showForumById(idShow);
                    String uri = "/forum.action?id=" + String.valueOf(idShow);
                    return new ForwardResolution(uri);
                } catch (NumberFormatException e) {
                    Logger.getLogger(DeleteMessageActionBean.class.getName()).log(Level.SEVERE, null, e);
                    return new ForwardResolution("/index.action");
                }
            }
        }

        /* Some error, show index */
        return new ForwardResolution("/index.action");
    }
}
